import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
import 'examples/layouts.dart';
import 'book.dart';
import 'network/data.dart';
import 'dart:async';
import 'dart:convert' show utf8, json;
import 'dart:io';

import 'login.dart';
import 'config.dart';


void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context){
    return new MaterialApp(
      title: "追小说",
      theme: new ThemeData(
        primaryColor: Colors.white
      ),
      home: new TabBarViewInited(),
    );
  }
}






class TabBarViewInited extends StatefulWidget {
  @override
  createState() => new TabBarViewController();
}


class TabBarViewController extends State<TabBarViewInited>{

  final _biggerFont = const TextStyle(fontSize: 16.0);

  final _suggestions = <WordPair>[];

  List bookdata;



  Widget isUpdated(bool isupdated){
    String text = "";
    if(isupdated){
      text = "更新";
    }
    return new Text(text);
  }

  Widget buildLastUpdateRow(String time,String lastChapter){
    if(time == "" && lastChapter == ""){
      return new Text("米有采集数据");
    }
    String lastUpdateStr = "";
    DateTime now = new DateTime.now();
    DateTime updateTime = DateTime.parse(time);
    Duration diff = now.difference(updateTime);
    print("时间相差");
    print(diff.inDays);
    if(diff.inDays < 1){
      print("小于1天");
      lastUpdateStr = diff.inHours.toString()+"小时前";
    }else{
      lastUpdateStr = diff.inDays.toString()+"天前";
    }
    String wholeText = lastUpdateStr+"  "+lastChapter;
    if(wholeText.length>20){
      wholeText = wholeText.substring(0,19)+"...";
    }
    return new Text(wholeText);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    RequestData requestData = new RequestData();
    Future<String> response = requestData.baseRequest(config.baseDomain, "/api/book/getall/2,3,4,5", "get");
    response.then((value) {
      print(value);
      Map data = json.decode(value);
      print(data["data"].length);
      this.setState(() {
        this.bookdata = data["data"];
      });
    }).catchError((err) {
      print(err);
      showDialog(context: context, child: new AlertDialog(
        title: new Text("错误"),
        content: new SingleChildScrollView(
          child: new ListBody(
            children: <Widget>[
              new Text("无法请求服务器数据"),
            ],
          ),
        ),
        actions: <Widget>[
          new FlatButton(onPressed: (){
            Navigator.of(context).pop();
          }, child: new Text("好的"))
        ],
      ));
    });

  }

  @override
  Widget build(BuildContext context) {

    Widget _buildRow(Map bookdata){


      return new ListTile(
//        leading: new Image.asset("images/180.jpeg"),
        leading: new Image.network(bookdata["surface"]),
        title: new Container(
          child: new Row(
            children: <Widget>[
              new Text(bookdata["name"]),
              isUpdated(false)
            ],
          ),
        ),
        subtitle: buildLastUpdateRow(bookdata["lastChapterUpdate"], bookdata["lastChapterName"]),
        onTap: (){
          Navigator.push(context, new MaterialPageRoute(builder: (context) => new BookBody(bookdata["bookid"])));
        },
      );
    }

    Widget _buildSuggestions(){
      return new ListView.builder(
          itemCount: this.bookdata == null ? 0 : this.bookdata.length*2,
          itemBuilder: (context,i){
            if(i.isOdd) return new Divider();
            final index = i ~/  2;
            print(i);
            return _buildRow(this.bookdata[index]);
          }
      );
    }



    return new DefaultTabController(
      length: 2,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text('追小说'),
          bottom: new TabBar(tabs: [
            new Container(
              height: 40.0,
              child: new Tab(text: '书架',),
            ),
            new Container(
              height: 40.0,
              child: new Tab(text: '社区',),
            ),

          ]),
          actions: <Widget>[
//          new IconButton(icon: new Icon(Icons.list), onPressed: _pushSaved)
            new IconButton(icon: new Icon(Icons.person), onPressed: (){
              Navigator.push(context, new MaterialPageRoute(builder: (context) => new LoginBody()));
            }),
            new IconButton(icon: new Icon(Icons.add), onPressed: (){

            }),
          ],
        ),

          body:new TabBarView(children: [
            _buildSuggestions(),
//            books,
            new Text('社区页面不会做好的'),

          ])
      ),
    );
  }
}
